package indi.zhifa.study2024.common.auth.sharding;

import indi.zhifa.core.common.util.CommonUtil;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 月表
 */
public class YearMonthTableShardingAlgorithm implements StandardShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        String tableName = shardingValue.getLogicTableName();
        Long billTimeSecond = shardingValue.getValue();
        LocalDateTime localDateTime = CommonUtil.parseFromSecond(billTimeSecond);
        int year = localDateTime.getYear();
        int monVal = localDateTime.getMonthValue();
        int season = (monVal+2)/3;
        if(year < 2022){
            return tableName+"_0";
        }else{
            return tableName+"_"+year+season;
        }
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        List<String> rtn = new ArrayList<String>();
        String tableName = rangeShardingValue.getLogicTableName();
        Long begTimeL = rangeShardingValue.getValueRange().lowerEndpoint();
        Long endTimeL = rangeShardingValue.getValueRange().upperEndpoint();
        LocalDateTime beginTime = CommonUtil.parseFromSecond(begTimeL);
        LocalDateTime endTime = CommonUtil.parseFromSecond(endTimeL);
        int yearBeg = beginTime.getYear();
        int yearEnd = endTime.getYear();
        int monBeg = beginTime.getMonthValue();
        int monEnd = endTime.getMonthValue();
        int seasonBeg = (monBeg+2)/3;
        int seasonEnd = (monEnd+2)/3;
        if(yearBeg < 2022){
            rtn.add(tableName+"_0");
            seasonBeg = 1;
            yearBeg = 2022;
        }

        for(int i = yearBeg; i <= yearEnd; i++){
            int curSeasonBeg = i > yearBeg ? 1:  seasonBeg;
            int curSeasonEnd = i < yearEnd ? 4 : seasonEnd;
            for(int j = curSeasonBeg; j <= curSeasonEnd; j++){
                rtn.add(tableName+"_"+i+""+j);
            }
        }
        return rtn;
    }

    @Override
    public String getType() {
        return "CUSTOM_YEAR_MONTH"; // 自定义算法类型名称
    }

}
